package com.sky.task;


import com.sky.constant.CommonConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务，检测下单支付超时和派送时间过长，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrdersTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理支付超时订单（超过15分钟算超时）
     * 每一分钟检测一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        //如果当前时间减去十五分钟大于下单时间，即超时（如果当前时间减去下单时间大于十五分钟，即超时）
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.getOrdersByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                //取消理由
                order.setCancelReason(CommonConstant.OVERTIME_PAYMENT);
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            });
        }
    }

    /**
     * 处理“派送中”状态的订单
     * 在每天的凌晨1点整检测一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理“派送中”状态的订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.getOrdersByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);

        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(time);
                ordersMapper.update(order);
            });
        }
    }
}
